package com.leetcodehot.problems;

import java.util.*;

public class problems107 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        if (root == null) return result;
        deque.addLast(root);
        while (!deque.isEmpty()) {
            int n = deque.size();
            List<Integer> ints = new ArrayList<>();
            while (n-- > 0) {
                TreeNode node = deque.removeFirst();
                ints.add(node.val);
                if (node.left != null) deque.addLast(node.left);
                if (node.right != null) deque.addLast(node.right);
            }
            result.add(ints);
        }
        Collections.reverse(result);
        return result;
    }
}
